package org.zht.dormpro.dorm.controller;

import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.zht.dormpro.pub.ResponseMap;
import org.zht.dormpro.pub.util.ExcelUtil;
import org.zht.dormpro.pub.util.UUIDUtil;
import org.zht.dormpro.pub.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.Iterator;

@Controller
@RequestMapping("dorm/upload")
@Log4j
public class UploadController {

    @RequestMapping("/uploadPage")
    public String uploadPage() {
        return "upload/upload";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public ResponseMap upload(@RequestParam("headPhoto") MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        String fileName = UUIDUtil.getUUID()+suffix;
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
           log.error("上传图片失败!");
        }
        String realpath = WebUtil.getPath(request).append("upload").append("/").append(fileName).toString();
        return ResponseMap.success(realpath);
    }
}